package com.robot.auth.filter;

import cn.hutool.core.util.StrUtil;
import com.robot.auth.entity.LoginUser;
import com.robot.auth.service.TokenService;
import com.robot.common.core.tool.Constants;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * Created by
 */
@Component
@AllArgsConstructor
public class JWTAuthorizationFilter extends OncePerRequestFilter {

    private TokenService tokenService;

    /*@Resource
    public void setTokenService(TokenService tokenService){
         JWTAuthorizationFilter.tokenService = tokenService;
    }*/


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
       // System.out.println(request);
        LoginUser loginUser = tokenService.getLoginUser(request);
        //System.out.println(loginUser);
        if(loginUser == null){
            chain.doFilter(request, response);
            return;
        }
        String tokenHeader = request.getHeader(Constants.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (!StrUtil.isNotEmpty(tokenHeader) || tokenHeader.equals("Bearer undefined") || !tokenHeader.startsWith(Constants.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        tokenService.verifyToken(loginUser);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request, response);
    }

}
